﻿$(document).ready(function () {
    $('#navbar-left li').each(function () {
        $(this).removeClass('active');
        if ($(this).find('i').hasClass('fa-bar-chart-o')) {
            $(this).addClass('active');
        }
    })
})

function AdminListBorrowDocument(total, pageSize, pageIndex, order, now) {

    //Private fileds
    var _pageSize = pageSize;
    var _pageIndex = pageIndex;
    var _total = total;
    var _order = order;
    var _now = now;
    var _baseUrl = '/api/ApiLibBorrowDocument/GetData';
    var _currentDocuments = 0;

    var _dataService = new DataService();

    //as
    this.Init = function () {
        Paging();
        DelegateEvent();
    };

    //private function
    function Paging() {
        var totalPages = (_total < pageSize) ? 1 : (Math.floor(_total / _pageSize) + 1);
        if (_total > 0) {
            var options = {
                bootstrapMajorVersion: 3,
                currentPage: _pageIndex,
                totalPages: totalPages,
                size: 'normal',
                useBootstrapTooltip: true,
                tooltipTitles: function (type, page, current) {
                    switch (type) {
                        case "first":
                            return "Về trang đầu";
                        case "prev":
                            return "Trang trước";
                        case "next":
                            return "Trang tiếp";
                        case "last":
                            return "Về trang cuối";
                        case "page":
                            return "Trang " + page;
                    }
                },
                onPageClicked: function (e, originalEvent, type, page) {
                    var url = _baseUrl + '?index=' + page + '&size=' + _pageSize + '&order=' + _order;

                    _dataService.Get(url, successCallback);
                }
            };
            $('#paging').bootstrapPaginator(options);
        }
    }

    function successCallback(data, textStatus, jqXHR) {
        InsertDocumentItem(data);
        if (data.total != _total) {
            var newTotal = (data.total < pageSize) ? 1 : (Math.floor(data.total / _pageSize) + 1);
            var newOptions = {
                totalPages: newTotal
            };
            $('#paging').bootstrapPaginator(newOptions);
        }
    }

    function InsertDocumentItem(data) {
        if (!data) {
            return;
        }
        $('#tableData>tbody').empty();
        var today = new Date(now);
        for (var i = 0; i < data.data.length; i++) {
            var status = '';
            var borrowDate = new Date(data.data[i].BorrowDate);
            //add BorrowDayCount to BorrowDate
            borrowDate.setDate(borrowDate.getDate() + data.data[i].BorrowDayCount);
            if (data.data[i].Status == 0) {
                if (borrowDate < today) {
                    status = '<span class="label label-danger">Chưa trả</span>'
                }
                else {
                    status = '<span class="label label-default">Chưa trả</span>'
                }
            }
            else if (data.data[i].Status == 1) {
                status = '<span>Đã trả</span>'
            }
            else if (data.data[i].Status == 2) {
                status = '<span class="text-warning">Đã trả</span>'
            }

            var html = '<tr>' +
                            '<td>' + data.data[i].BorrowDocumentId + '</td>' +
                            '<td>' + ((data.data[i].DocumentName != null) ? data.data[i].DocumentName : '') + '</td>' +
                            '<td>' + ((data.data[i].UserName != null) ? data.data[i].UserName : '') + '</td>' +
                            '<td>' + ((data.data[i].BorrowDate != null) ? new Date(data.data[i].BorrowDate).format('dd/mm/yyyy') : '01/01/2013') + '</td>' +
                            '<td>' + ((data.data[i].Total != null) ? data.data[i].Total : '') + '</td>' +
                            '<td>' + ((data.data[i].BorrowDayCount != null) ? data.data[i].BorrowDayCount : '') + '</td>' +
                            '<td>' + ((data.data[i].ReturnDate != null) ? new Date(data.data[i].ReturnDate).format('dd/mm/yyyy') : '') + '</td>' +
                            '<td>' + status + '</td>' +
                            '<td>' +
                                '<button class="btn btn-default btn-xs table-action" style="margin-right:7px;" value="' + ((data.data[i].BorrowDocumentId != null) ? data.data[i].BorrowDocumentId : '#') + '"><i class="fa fa-credit-card"></i></button>' +
                            '</td>' +
                       '</tr>';
            $('#tableData>tbody').append(html);
        }
    }

    function DelegateEvent() {
        $('#mdocumentName').change(function (d) {
            $('#mdocumentName option[value=0]').remove();
            var documentId = $('#mdocumentName').val();
            _dataService.Get('/api/ApiLibDocuments/GetCurrentTotalInLib?documentId=' + documentId, function (data, textStatus, jqXHR) {
                if (data.success) {
                    _currentDocuments = data.currentDocument;
                    $('#mtotal').attr('placeholder', 'Mượn tối đa: ' + _currentDocuments);
                }
            });
        });

        //Edit
        $('#tableData>tbody').delegate('td>button', 'click', function (e) {
            e.preventDefault();
            var self = $(this);
            var pos = self.closest('tr').index();
            if (pos != null) {
                if (self.find('i').hasClass('fa-credit-card')) {
                    _dataService.Post('/api/ApiLibBorrowDocument/ReturnDocument?borrowDocumentId=' + self.attr('value'), null, function (data, textStatus, jqXHR) {
                        if (data.success) {
                            var today = new Date(data.currentBorrowDate);
                            var status = '';
                            var borrowDate = new Date(data.currentBorrowDate);
                            //add BorrowDayCount to BorrowDate
                            borrowDate.setDate(borrowDate.getDate() + data.data.BorrowDayCount);
                            if (data.data.Status == 0) {
                                if (borrowDate < today) {
                                    status = '<span class="label label-danger">Chưa trả</span>'
                                }
                                else {
                                    status = '<span class="label label-default">Chưa trả</span>'
                                }
                            }
                            else if (data.data.Status == 1) {
                                status = '<span>Đã trả</span>'
                            }
                            else if (data.data.Status == 2) {
                                status = '<span class="text-warning">Đã trả</span>'
                            }
                            self.find('td').each(function (i, d) {
                                if (i == 8) {
                                    d.empty();
                                    d.append(status);
                                }
                            });
                        }
                    });
                }
            }
        });

        //Addnew
        $('#addNew').click(function () {
            //Add Documents
            _dataService.Get('/api/ApiLibDocuments/GetData?index=1&size=50000&order=DocumentName', function (data, textStatus, jqXHR) {
                if (data.success == true) {
                    $('#mdocumentName').empty();
                    for (var document = 0; document < data.data.length; document++) {
                        var html = '<option value="' + data.data[document].DocumentId + '">' + data.data[document].DocumentName + '</option>';
                        $('#mdocumentName').append(html);
                    }
                    $('#mdocumentName').prepend('<option value="0">-- Chọn tài liệu --</option>');
                    $('#mdocumentName').val(0);
                }
            });
            //Add User
            _dataService.Get('/api/ApiLibUser/GetData?index=1&size=50000', function (data, textStatus, jqXHR) {
                if (data.success == true) {
                    $('#muser').empty();
                    for (var user = 0; user < data.data.length; user++) {
                        var html = '<option value="' + data.data[user].UserID + '">' + data.data[user].UserName + '</option>';
                        $('#muser').append(html);
                    }
                }
            });
            $('#mtotal').val();
            $('#mtotal').attr('placeholder', 'Số lượng');
            $('#mborrowDayCount').val();
            $('#mborrowReason').val();
            //Reset validate state
            $('#myModal-alerts').empty();
            $('#mdocumentName').closest('.form-group').removeClass('has-error');
            $('#mtotal').closest('.form-group').removeClass('has-error');
            $('#mborrowDayCount').closest('.form-group').removeClass('has-error');
            $('#myModalLabel').text('Tạo phiếu mượn tài liệu');
            $('#myModalFooter>.btn-primary').attr('value', 'addnew');
            $('#myModal').modal('show');
        });

        //Save
        $('#myModalFooter .btn-primary').click(function () {
            var self = $(this);
            if (self.attr('value') == 'addnew') {
                //Validate
                var isValid = Validate();
                if (!isValid) {
                    return;
                }
                //Do Action
                var data = {
                    DocumentId: ($('#mdocumentName').val() == '' ? null : $('#mdocumentName').val()),
                    UserId: ($('#muser').val() == '' ? null : $('#muser').val()),
                    Total: ($('#mtotal').val() == '' ? null : $('#mtotal').val()),
                    BorrowDate: $('#datetimepicker10').data("DateTimePicker").getDate().format("MM/DD/YYYY HH:mm:ss"),
                    BorrowDayCount: ($('#mborrowDayCount').val() == '' ? null : $('#mborrowDayCount').val()),
                    Reason: ($('#mborrowReason').val() == '' ? null : $('#mborrowReason').val())
                };
                _dataService.Post('/api/ApiLibBorrowDocument/CreateData', data, function (data, textStatus, jqXHR) {
                    if (data.success) {
                        var today = new Date(now);
                        var status = '';
                        var borrowDate = new Date(data.data.BorrowDate);
                        //add BorrowDayCount to BorrowDate
                        borrowDate.setDate(borrowDate.getDate() + data.data.BorrowDayCount);
                        if (data.data.Status == 0) {
                            if (borrowDate < today) {
                                status = '<span class="label label-danger">Chưa trả</span>'
                            }
                            else {
                                status = '<span class="label label-default">Chưa trả</span>'
                            }
                        }
                        else if (data.data.Status == 1) {
                            status = '<span>Đã trả</span>'
                        }
                        else if (data.data.Status == 2) {
                            status = '<span class="text-warning">Đã trả</span>'
                        }
                        var html = '<tr>' +
                                        '<td>' + data.data.BorrowDocumentId + '</td>' +
                                        '<td>' + ((data.data.DocumentName != null) ? data.data.DocumentName : $('#mdocumentName option[value="' + data.data.DocumentId + '"]').text()) + '</td>' +
                                        '<td>' + ((data.data.UserName != null) ? data.data.UserName : $('#muser option[value="' + data.data.UserId + '"]').text()) + '</td>' +
                                        '<td>' + ((data.data.BorrowDate != null) ? moment(data.data.BorrowDate).format("DD/MM/YYYY") : '01/01/2013') + '</td>' +
                                        '<td>' + ((data.data.Total != null) ? data.data.Total : '') + '</td>' +
                                        '<td>' + ((data.data.BorrowDayCount != null) ? data.data.BorrowDayCount : '') + '</td>' +
                                        '<td>' + ((data.data.ReturnDate != null) ? moment(data.data.ReturnDate).format("DD/MM/YYYY") : '') + '</td>' +
                                        '<td>' + status + '</td>' +
                                        '<td>' +
                                            //'<button class="btn btn-default btn-xs table-action" style="margin-right:7px;" value="' + ((data.data.BorrowDocumentId != null) ? data.data.BorrowDocumentId : '#') + '"><i class="fa fa-info-circle"></i></button>' +
                                            '<button class="btn btn-default btn-xs table-action" style="margin-right:7px;" value="' + ((data.data.BorrowDocumentId != null) ? data.data.BorrowDocumentId : '#') + '"><i class="fa fa-credit-card"></i></button>' +
                                        '</td>' +
                                   '</tr>';
                        $('#tableData>tbody').prepend(html);

                        window.open('/report/regborrow/' + data.data.BorrowDocumentId, '_blank');
                        $('#myModal').modal('hide');
                    }
                });                                     
            }
        });
    }

    function Validate() {
        $('#myModal-alerts').empty();
        $('#mdocumentName').closest('.form-group').removeClass('has-error');
        $('#mtotal').closest('.form-group').removeClass('has-error');
        $('#mborrowDayCount').closest('.form-group').removeClass('has-error');
        var isError = false;
        var errCount = 0;
        var errMessage = '';
        var mdocumentName = $('#mdocumentName').val();
        var mtotal = $('#mtotal').val();
        if (mdocumentName == null || isNaN(mdocumentName) || mdocumentName.trim().length === 0 || mdocumentName <= 0) {
            isError = true;
            errCount++;
            errMessage += '<p>' + errCount + '. Chọn tài liệu cần mượn.</p>';
            $('#mdocumentName').closest('.form-group').addClass('has-error');
        }        
        else if (mtotal == null || isNaN(mtotal) || mtotal.trim().length === 0 || mtotal > _currentDocuments) {
            isError = true;
            errCount++;
            errMessage += '<p>' + errCount + '. Nhập số lượng tài liệu cần mượn. Tối đa: ' + _currentDocuments + '.</p>';
            $('#mtotal').closest('.form-group').addClass('has-error');
        }
        var mborrowDayCount = $('#mborrowDayCount').val();
        if (mborrowDayCount == null || isNaN(mborrowDayCount) || mborrowDayCount.trim().length === 0 || mborrowDayCount <= 0) {
            isError = true;
            errCount++;
            errMessage += '<p>' + errCount + '. Nhập số ngày mượn tài liệu.</p>';
            $('#mborrowDayCount').closest('.form-group').addClass('has-error');
        }

        //Show alert        
        var alertError = '<div class="alert alert-danger alert-dismissable">' +
                             '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' +
                             '<strong>Có ' + errCount + ' lỗi nhập liệu.</strong> Xin hãy nhập lại.' +
                             '<p>Thông tin lỗi:</p>' +
                             errMessage +
                         '</div>';
        $('#myModal-alerts').prepend(alertError);
        return !isError;
    }
}